<template>
  <view class="container">
    <!-- ECharts 图表 -->
    <echarts :option="chartOption" style="height: 600rpx;" />
    
    <!-- 仓库选择器 -->
    <picker @change="onWarehouseChange" :range="warehouses">
      <view class="picker">当前仓库: {{ warehouses[selectedWhIndex] }}</view>
    </picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedWhIndex: 0,    // 当前选中的仓库索引
      warehouses: [],         // 仓库列表
      chartOption: {          // ECharts配置
        tooltip: {},
        xAxis: { data: [] },
        yAxis: {},
        series: [{ type: 'bar', data: [] }]
      }
    }
  },
  mounted() {
    this.fetchWarehouses()
    this.fetchInventoryData()
  },
  methods: {
    async fetchWarehouses() {
      // 获取仓库列表
      const res = await uni.request({ url: '/api/warehouses/' })
      this.warehouses = res.data.map(wh => wh.name)
    },
    async fetchInventoryData() {
      // 获取库存数据并更新图表
      const res = await uni.request({
        url: `/api/inventory/${this.warehouses[this.selectedWhIndex].id}`
      })
      this.chartOption.xAxis.data = res.data.map(item => item.material_name)
      this.chartOption.series[0].data = res.data.map(item => item.quantity)
    },
    onWarehouseChange(e) {
      this.selectedWhIndex = e.detail.value
      this.fetchInventoryData()
    }
  }
}
</script>